import React, { useState, useRef } from 'react';

interface AppItem {
  id: string;
  name: string;
  icon: string;
  color: string;
  desc: string;
  website: string;
  category?: string; // 添加类别属性
}

// 完整应用列表（包含微信、QQ、抖音等需求应用，以及对应的官网链接）
const appList: AppItem[] = [
  { id: '1', name: '微信', icon: '💬', color: '#07C160', desc: '即时通讯', website: 'https://weixin.qq.com/', category: '社交通讯' },
  { id: '2', name: 'QQ', icon: '🐧', color: '#12B7F5', desc: '社交娱乐', website: 'https://im.qq.com/', category: '社交通讯' },
  { id: '3', name: '抖音', icon: '🎬', color: '#FE2C55', desc: '短视频平台', website: 'https://www.douyin.com/', category: '影音娱乐' },
  { id: '4', name: '网易云音乐', icon: '🎵', color: '#C20C0C', desc: '音乐播放', website: 'https://music.163.com/', category: '音乐音频' },
  { id: '5', name: '快手', icon: '📹', color: '#00C65E', desc: '短视频平台', website: 'https://www.kuaishou.com/', category: '影音娱乐' },
  { id: '6', name: '小红书', icon: '📚', color: '#FF2442', desc: '生活分享', website: 'https://www.xiaohongshu.com/', category: '社交通讯' },
  { id: '7', name: '浏览器', icon: '🌐', color: '#4285F4', desc: '网页浏览', website: 'https://www.baidu.com/', category: '生活工具' },
  { id: '8', name: '电脑计算器', icon: '🧮', color: '#9C27B0', desc: '系统计算工具', website: 'https://www.xbgjw.com/jisuanqi', category: '生活工具' },
  { id: '9', name: '微博', icon: '📊', color: '#E6162D', desc: '社交媒体', website: 'https://weibo.com/', category: '社交通讯' },
  { id: '10', name: '哔哩哔哩', icon: '📺', color: '#00A1D6', desc: '视频平台', website: 'https://www.bilibili.com/', category: '影音娱乐' }
];

// 收纳类别定义
const categories = [
  { id: 'social', name: '社交通讯', icon: '📱', apps: [] as AppItem[] },
  { id: 'entertainment', name: '影音娱乐', icon: '🎬', apps: [] as AppItem[] },
  { id: 'tools', name: '生活工具', icon: '📚', apps: [] as AppItem[] },
  { id: 'music', name: '音乐音频', icon: '🎵', apps: [] as AppItem[] }
];

const AppsPage: React.FC = () => {
  // 使用useState管理可拖拽的应用列表和拖拽状态
  const [apps, setApps] = useState<AppItem[]>(appList);
  const [organizedCategories, setOrganizedCategories] = useState(categories);
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
  const [draggedItem, setDraggedItem] = useState<AppItem | null>(null);
  const [dragSource, setDragSource] = useState<'appList' | 'category' | null>(null);
  const [dragCategoryId, setDragCategoryId] = useState<string | null>(null);
  const draggedItemRef = useRef<HTMLElement | null>(null);
  
  // 处理应用点击事件，跳转到对应官网
  const handleAppClick = (website: string) => {
    // 在新标签页打开对应的官网链接
    window.open(website, '_blank');
  };
  
  // 处理拖拽开始
  const handleDragStart = (e: React.DragEvent, index: number, source: 'appList' | 'category', categoryId?: string) => {
    const item = source === 'appList' ? apps[index] : organizedCategories.find(cat => cat.id === categoryId)?.apps[index];
    if (!item) return;
    
    setDraggedIndex(index);
    setDraggedItem(item);
    setDragSource(source);
    setDragCategoryId(categoryId || null);
    draggedItemRef.current = e.currentTarget as HTMLElement;
    // 设置拖拽时的透明度效果
    (e.currentTarget as HTMLElement).style.opacity = '0.5';
    // 设置拖拽时的视觉样式
    e.dataTransfer.effectAllowed = 'move';
    // 设置拖拽数据
    e.dataTransfer.setData('text/plain', JSON.stringify({ index, source, categoryId }));
  };
  
  // 处理拖拽结束
  const handleDragEnd = (e: React.DragEvent) => {
    (e.currentTarget as HTMLElement).style.opacity = '1';
    setDraggedIndex(null);
    setHoveredIndex(null);
    setDraggedItem(null);
    setDragSource(null);
    setDragCategoryId(null);
    draggedItemRef.current = null;
    // 清除所有元素的拖拽样式
    document.querySelectorAll('.app-item, .category-app-item').forEach(item => {
      const element = item as HTMLElement;
      element.style.boxShadow = '';
      element.style.transform = '';
    });
  };
  
  // 允许放置
  const handleDragOver = (e: React.DragEvent, index: number, target: 'appList' | 'category') => {
    e.preventDefault(); // 允许放置
    e.dataTransfer.dropEffect = 'move';
    
    // 如果是在应用列表内部拖拽，添加视觉反馈
    if (target === 'appList' && dragSource === 'appList' && index >= 0) {
      setHoveredIndex(index);
      
      // 给悬停的元素添加视觉反馈
      const targetElement = e.currentTarget as HTMLElement;
      targetElement.style.boxShadow = '0 8px 20px rgba(217, 70, 239, 0.3)';
      targetElement.style.transform = 'scale(1.05)';
      
      // 清除其他元素的反馈
      document.querySelectorAll('.app-item').forEach(item => {
        if (item !== targetElement) {
          const element = item as HTMLElement;
          element.style.boxShadow = '';
          element.style.transform = '';
        }
      });
    }
  };
  
  // 处理拖拽离开
  const handleDragLeave = (e: React.DragEvent) => {
    // 仅当完全离开元素时才清除样式
    setTimeout(() => {
      // 确保currentTarget存在
      if (e.currentTarget) {
        const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
        const { clientX, clientY } = e;
        if (clientX < rect.left || clientX > rect.right || 
            clientY < rect.top || clientY > rect.bottom) {
          (e.currentTarget as HTMLElement).style.boxShadow = '';
          (e.currentTarget as HTMLElement).style.transform = '';
          setHoveredIndex(null);
        }
      }
    }, 10);
  };
  
  // 处理放置
  const handleDrop = (e: React.DragEvent, target: 'appList' | 'category', categoryId?: string) => {
    e.preventDefault();
    
    // 清除视觉反馈
    document.querySelectorAll('.app-item, .category-app-item').forEach(item => {
      const element = item as HTMLElement;
      element.style.boxShadow = '';
      element.style.transform = '';
    });
    
    if (!draggedItem || !dragSource) return;
    
    // 如果是在应用列表内部拖拽，实现位置互换
    if (dragSource === 'appList' && target === 'appList' && draggedIndex !== null && hoveredIndex !== null && draggedIndex !== hoveredIndex) {
      // 创建新的应用列表，实现两个应用位置互换
      const newApps = [...apps];
      // 确保索引有效
      if (draggedIndex >= 0 && draggedIndex < newApps.length && hoveredIndex >= 0 && hoveredIndex < newApps.length) {
        // 交换两个应用的位置
        [newApps[draggedIndex], newApps[hoveredIndex]] = [newApps[hoveredIndex], newApps[draggedIndex]];
        
        // 更新状态
        setApps(newApps);
      }
    }
    // 如果是从应用列表拖到收纳类别
    else if (dragSource === 'appList' && target === 'category' && categoryId) {
      moveAppToCategory(draggedIndex!, categoryId);
    }
    // 如果是从收纳类别拖到应用列表
    else if (dragSource === 'category' && target === 'appList' && dragCategoryId) {
      moveAppToAppList(draggedIndex!, dragCategoryId);
    }
    // 如果是在收纳类别之间移动
    else if (dragSource === 'category' && target === 'category' && dragCategoryId && categoryId && dragCategoryId !== categoryId) {
      moveAppBetweenCategories(draggedIndex!, dragCategoryId, categoryId);
    }
    
    setHoveredIndex(null);
  };
  
  // 将应用移动到收纳类别
  const moveAppToCategory = (appIndex: number, targetCategoryId: string) => {
    const newApps = [...apps];
    const removedApp = newApps.splice(appIndex, 1)[0];
    
    const newCategories = organizedCategories.map(cat => {
      if (cat.id === targetCategoryId) {
        return { ...cat, apps: [...cat.apps, removedApp] };
      }
      return cat;
    });
    
    setApps(newApps);
    setOrganizedCategories(newCategories);
  };
  
  // 将应用从收纳类别移回应用列表
  const moveAppToAppList = (appIndex: number, sourceCategoryId: string) => {
    const sourceCategory = organizedCategories.find(cat => cat.id === sourceCategoryId);
    if (!sourceCategory) return;
    
    const newCategories = organizedCategories.map(cat => {
      if (cat.id === sourceCategoryId) {
        const newApps = [...cat.apps];
        newApps.splice(appIndex, 1);
        return { ...cat, apps: newApps };
      }
      return cat;
    });
    
    // 将应用添加回应用列表
    const movedApp = sourceCategory.apps[appIndex];
    const newApps = [...apps, movedApp];
    
    setApps(newApps);
    setOrganizedCategories(newCategories);
  };
  
  // 在收纳类别之间移动应用
  const moveAppBetweenCategories = (appIndex: number, sourceCategoryId: string, targetCategoryId: string) => {
    const sourceCategory = organizedCategories.find(cat => cat.id === sourceCategoryId);
    if (!sourceCategory) return;
    
    const newCategories = organizedCategories.map(cat => {
      // 从源类别移除应用
      if (cat.id === sourceCategoryId) {
        const newApps = [...cat.apps];
        newApps.splice(appIndex, 1);
        return { ...cat, apps: newApps };
      }
      // 向目标类别添加应用
      if (cat.id === targetCategoryId) {
        const sourceApp = sourceCategory.apps[appIndex];
        return { ...cat, apps: [...cat.apps, sourceApp] };
      }
      return cat;
    });
    
    setOrganizedCategories(newCategories);
  };
  
  // 处理收纳类别拖拽放置
  const handleCategoryDrop = (e: React.DragEvent, categoryId: string) => {
    e.preventDefault();
    handleDrop(e, 'category', categoryId);
  };

  return (
    <div
      style={{
        // 移除固定左边距，使用自适应布局
        marginLeft: '0',
        height: '100vh',
        background: 'rgba(255, 248, 250, 1)',
        // 使用百分比padding，使内容自适应
        padding: '2%',
        color: '#333',
        // 防止水平滚动
        overflowX: 'hidden',
        boxSizing: 'border-box',
      }}
    >
      <h1 style={{ color: '#d946ef', marginBottom: '40px', fontSize: '28px' }}>应用库</h1>
      <div
        style={{
          display: 'grid',
          // 使用auto-fit和minmax实现自适应网格
          gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
          gap: '24px',
          // 移除固定最大宽度，使用100%自适应
          width: '100%',
          margin: '0 auto',
          boxSizing: 'border-box',
        }}
        onDragOver={(e) => {
          e.preventDefault();
          e.dataTransfer.dropEffect = 'move';
        }}
        onDrop={(e) => handleDrop(e, 'appList')}
      >
        {apps.map((app, index) => (
          <div
            key={app.id}
            className="app-item"
            style={{
              background: 'white',
              borderRadius: '16px',
              padding: '20px',
              boxShadow: '0 4px 12px rgba(255, 182, 193, 0.1)',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              textAlign: 'center',
              cursor: 'grab', // 显示可抓取的鼠标样式
              transition: 'all 0.3s ease', // 增强过渡效果
              opacity: draggedIndex === index && dragSource === 'appList' ? 0.8 : 1, // 拖拽时的透明度
              transform: hoveredIndex === index ? 'scale(1.05)' : 'scale(1)', // 悬停时的缩放效果
            }}
            onMouseEnter={(e) => { if (draggedIndex === null) e.currentTarget.style.transform = 'translateY(-5px)' }}
            onMouseLeave={(e) => { if (draggedIndex === null) e.currentTarget.style.transform = 'translateY(0)' }}
            onMouseDown={(e) => (e.currentTarget.style.cursor = 'grabbing')} // 按下时显示抓取中样式
            onMouseUp={(e) => (e.currentTarget.style.cursor = 'grab')}
            onClick={() => handleAppClick(app.website)}
            // 拖拽相关事件
            draggable
            onDragStart={(e) => handleDragStart(e, index, 'appList')}
            onDragEnd={handleDragEnd}
            onDragOver={(e) => handleDragOver(e, index, 'appList')}
            onDragLeave={handleDragLeave}
            onDrop={(e) => handleDrop(e, 'appList')}
          >
            <div
              style={{
                width: '60px',
                height: '60px',
                borderRadius: '50%',
                background: `${app.color}20`, // 浅色背景
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginBottom: '16px',
              }}
            >
              <span style={{ fontSize: '28px', color: app.color }}>{app.icon}</span>
            </div>
            <h3 style={{ margin: '0 0 8px 0', color: '#333' }}>{app.name}</h3>
            <p style={{ color: '#999', fontSize: '12px', margin: 0 }}>{app.desc}</p>
          </div>
        ))}
      </div>

      {/* 添加手机收纳类表功能 */}
      <div
        style={{
          marginTop: '50px',
          padding: '30px',
          background: 'white',
          borderRadius: '16px',
          boxShadow: '0 4px 12px rgba(255, 182, 193, 0.1)',
        }}
      >
        <h2 style={{ 
          color: '#d946ef', 
          marginBottom: '20px', 
          fontSize: '24px',
          textAlign: 'center'
        }}>
           可以移动收纳盒
        </h2>
        
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
            gap: '15px',
          }}
        >
          {/* 收纳类别 */}
          {organizedCategories.map((category) => (
            <div
              key={category.id}
              style={{
                background: 'rgba(217, 70, 239, 0.1)',
                borderRadius: '12px',
                padding: '15px',
                textAlign: 'center',
                cursor: 'pointer',
                transition: 'all 0.3s ease',
              }}
              onDragOver={(e) => handleDragOver(e, -1, 'category')}
              onDrop={(e) => handleCategoryDrop(e, category.id)}
            >
              <div style={{ fontSize: '24px', marginBottom: '8px' }}>{category.icon}</div>
              <h3 style={{ margin: '0 0 5px 0', color: '#d946ef' }}>{category.name}</h3>
              <p style={{ color: '#666', fontSize: '12px', margin: '0 0 10px 0' }}>{category.apps.length} 个应用</p>
              
              {/* 类别中的应用 */}
              <div
                style={{
                  display: 'grid',
                  gridTemplateColumns: 'repeat(3, 1fr)',
                  gap: '8px',
                  marginTop: '10px',
                }}
              >
                {category.apps.map((app, index) => (
                  <div
                    key={`${category.id}-${app.id}`}
                    className="category-app-item"
                    style={{
                      width: '40px',
                      height: '40px',
                      borderRadius: '8px',
                      background: `${app.color}20`,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      cursor: 'grab',
                      fontSize: '18px',
                      color: app.color,
                      transition: 'all 0.2s ease',
                    }}
                    draggable
                    onDragStart={(e) => handleDragStart(e, index, 'category', category.id)}
                    onDragEnd={handleDragEnd}
                    onDragOver={(e) => handleDragOver(e, index, 'category')}
                    onDrop={(e) => handleDrop(e, 'category', category.id)}
                    title={app.name}
                  >
                    {app.icon}
                  </div>
                ))}
                
                {/* 添加放置区域 */}
                <div
                  style={{
                    width: '40px',
                    height: '40px',
                    borderRadius: '8px',
                    border: '2px dashed #d946ef',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    cursor: 'pointer',
                    fontSize: '18px',
                    color: '#d946ef',
                  }}
                  onDragOver={(e) => handleDragOver(e, -1, 'category')}
                  onDrop={(e) => handleCategoryDrop(e, category.id)}
                >
                  +
                </div>
              </div>
            </div>
          ))}
        </div>
        
        {/* 添加说明文字 */}
        <div style={{ 
          marginTop: '25px', 
          textAlign: 'center', 
          color: '#999', 
          fontSize: '14px',
          padding: '15px',
          background: 'rgba(217, 70, 239, 0.05)',
          borderRadius: '8px'
        }}>
          <p>💡 拖拽应用图标可在应用库和收纳类别之间移动</p>
          <p>📱 点击应用图标可打开对应网站</p>
        </div>
      </div>
    </div>
  );
};

// 添加响应式CSS样式
const style = document.createElement('style');
style.innerHTML = `
  @media (max-width: 768px) {
    .app-item {
      padding: 15px !important;
    }
    
    .app-item h3 {
      font-size: 16px !important;
    }
    
    .app-item p {
      font-size: 11px !important;
    }
  }
  
  @media (max-width: 480px) {
    .app-item {
      padding: 12px !important;
    }
    
    .app-item h3 {
      font-size: 14px !important;
    }
    
    .app-item p {
      font-size: 10px !important;
    }
  }
`;
document.head.appendChild(style);

export default AppsPage;